package com.xuan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xuan.common.util.PageResult;
import com.xuan.entity.Classes;
import com.xuan.entity.Student;
import com.xuan.mapper.StudentMapper;
import com.xuan.service.IClassesService;
import com.xuan.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.valueobject.ValueObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuan
 * @since 2025-01-07
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {


        @Autowired
        private IClassesService classesService;
    // 分页查询
    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize) {
        //  自己配置了分页接口
        Page<Student> page1 = this.page(new Page<>(page, pageSize));

        //  封装分页结果
        return new PageResult<>(page1.getRecords(),page1.getTotal());
    }



    @Override
    public PageResult<Student> find(Integer page, Integer pageSize, ValueObject vo) {
        // 创建分页对象
        Page<Student> studentPage = new Page<>(page, pageSize);

        // 构建查询条件
        QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(vo.getSname())) {
            queryWrapper.like("sname", vo.getSname());
        }
        if (StrUtil.isNotBlank(vo.getAddr())) {
            queryWrapper.like("addr", vo.getAddr());
        }
        if (vo.getCid() != null && vo.getCid() != 0) {
            queryWrapper.eq("cid", vo.getCid());
        }

        // 执行分页查询
        studentPage = this.page(studentPage, queryWrapper);

        // 获取学生列表并设置班级名称
        List<Student> students = studentPage.getRecords();

        Map<Integer, String> classMap = students.stream()
                .filter(st -> st.getCid() != null)
                .map(Student::getCid)
                .distinct()
                .collect(Collectors.toMap(
                        cid -> cid,
                        cid -> classesService.getById(cid).getCname()
                ));

        students.forEach(st -> {
            if (st.getCid() != null) {
                st.setCname(classMap.get(st.getCid()));
            }
        });

        return new PageResult<>(students, studentPage.getTotal());
    }
    // 添加学生
    @Override
    public boolean add(Student student) {
        return this.save(student);
    }



}
